package com.lt.flashcard.view;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;

import com.lt.flashcard.Utility;
import com.lt.flashcard.model.entity.Productcategory;
import com.lt.flashcard.model.service.AAService;
import com.lt.flashcard.model.service.EcommerceService;
import com.lt.flashcard.model.service.Repository;

public class AdminProductCategoryVm {
	
	private List<Productcategory> categories;
	private Productcategory category = null; //Store current top category
	
	@Init
	public void init() {
		AAService srv  = Repository.getInstance().getAAService();
		if(!srv.isLogin() || !srv.hasRole("admin")) {
			Utility.adminLoginOrAccessDenied(false);
		}
		
		loadCategories();
	}
	
	private void loadCategories() {
		EcommerceService srv = Repository.getInstance().getEcommerceService();
		if(getCategory() == null) {
			setCategories(srv.getParentProductCategories());
		}
		else {
			categories = getCategory().getChild();
		}
	}
	
	@NotifyChange("categories")
	@Command
	public void addnew(@BindingParam("name") String name) {
		if(StringUtils.isNotBlank(name)) {
			EcommerceService srv = Repository.getInstance().getEcommerceService();
			Productcategory cat = new Productcategory();
			cat.setName(name);
			if(category != null) {
				cat.setParent(category);
				category.getChild().add(cat);
				srv.saveProductCategory(category);
			}
			else {
				srv.saveProductCategory(cat);
			}
			loadCategories();
		}
	}
	
	@NotifyChange("categories")
	@Command
	public void delete(@BindingParam("id") Long id) {
		if(id > 0l) {
			EcommerceService srv = Repository.getInstance().getEcommerceService();
			Productcategory cat = category.removeChild(id);
			if(cat != null) {
				srv.deleteProductCategory(cat);
				srv.saveProductCategory(category);
			}
			loadCategories();
		}
	}
	
	@NotifyChange({"categories", "category"})
	@Command
	public void detail(@BindingParam("id") Long id) {
		if(id > 0l) {
			EcommerceService srv = Repository.getInstance().getEcommerceService();
			setCategory(srv.getProductCategory(id));
			loadCategories();
		}
	}
	
	@NotifyChange({"categories", "category"})
	@Command
	public void up() {
		if(getCategory() != null) {
			setCategory(getCategory().getParent());
			loadCategories();
		}
	}

	public List<Productcategory> getCategories() {
		return categories;
	}

	public void setCategories(List<Productcategory> categories) {
		this.categories = categories;
	}

	public Productcategory getCategory() {
		return category;
	}

	public void setCategory(Productcategory category) {
		this.category = category;
	}
}
